package com.example.base.mvvm

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.*
import com.blankj.utilcode.util.ToastUtils
import com.example.base.entity.Res
import com.google.gson.Gson
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

open class BaseViewModel : ViewModel() {

    fun <T> httpRequest(s:suspend ()-> Res<T>,success:(T) ->Unit){
        viewModelScope.launch{
            try {
                val res = s.invoke()
                if(res.code == 200){
                    success(res.data)
                }else{
                    ToastUtils.showLong(res.message)
                }
            }catch (e:Exception){
                Log.i("TAG", e.message.toString())
            }
        }
    }

    fun <T:Any> httpRequestFlow(pagingSourceFactory: () -> PagingSource<Int, T>):Flow<PagingData<T>>{
        return Pager(config = PagingConfig(10),
            pagingSourceFactory =pagingSourceFactory
        ).flow.cachedIn(viewModelScope)
    }

    fun toBody(item:Any): RequestBody {
        val toJson = Gson().toJson(item)
        val body = RequestBody.create("application/json".toMediaTypeOrNull(),toJson)
        return body
    }

}